package com.ai.networking.IXCom;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.Socket;
import java.util.LinkedList;

@Data
@Component
@Slf4j
public class IXComClientTangent {

    public static IXComClientTangent ixComClientTangent;

    private Socket socket;
    private BufferedReader in;
    private OutputStream out;

    public static int connectSize = 0;
    public static int errorSize = 0;
    public static int failedSize = 0;

    private LinkedList<String> list = new LinkedList<>();
    private boolean inputFlag = false;
    private boolean socketState = false;

    public void start() {
        ixComClientTangent = this;

        connect();
    }

    public void connect() {
        try {
            if (!socketState) {
                log.info("ip=" + CommonIXCom.L3_IP + ";serverPort=" + CommonIXCom.L3_SERVER_PORT);
                socket = new Socket(CommonIXCom.L3_IP, CommonIXCom.L3_SERVER_PORT);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
                out = socket.getOutputStream();
                socketState = true;
                log.info("客户端第 " + (++connectSize) + " 次连接服务器");
                receive();
            }
        } catch (Exception e) {
            socketState = false;
            log.error("客户端 第 " + (++failedSize) + " 次 无法连接到服务器，或连接已断开:" + e.getMessage());
        }
    }

    public void send(String msg) {
        inputFlag = true;//进入输入状态
        try {
            log.info("客户端发送：" + msg);
            PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(out, "UTF-8"));
            printWriter.write(msg);
            printWriter.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        inputFlag = false;//非输入状态
        synchronized (list) {
            list.notifyAll();//通知等待的打印线程继续打印
        }
    }

    public void receive() {
        new Thread(() -> {
            try {
                while (socketState) {
                    log.info("------------------------- 客户端等待服务端的消息 --------------------------");
                    String msg = in.readLine();
                    if (!StringUtils.isEmpty(msg)) {
                        log.info(" 连接客户端接收：" + msg);
                    }
                }
            } catch (Exception e) {
                socketState = false;
                log.error("客户端 第 " + (++errorSize) + " 次与服务器断开连接:" + e.getMessage());
            }
        }).start();
    }
}